#include "online_status_service.h"

// 设置用户在线状态
int set_online_status(sqlite3 *db, int user_id, int is_online) {
    char *sql = "INSERT INTO online_status (user_id, is_online, last_active) "
                "VALUES (?, ?, datetime('now')) "
                "ON CONFLICT(user_id) DO UPDATE SET "
                "is_online = excluded.is_online, "
                "last_active = datetime('now');";
    
    sqlite3_stmt *stmt;
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
        return -1;
    }
    
    sqlite3_bind_int(stmt, 1, user_id);
    sqlite3_bind_int(stmt, 2, is_online);
    
    rc = sqlite3_step(stmt);
    if (rc != SQLITE_DONE) {
        fprintf(stderr, "Update failed: %s\n", sqlite3_errmsg(db));
        sqlite3_finalize(stmt);
        return -1;
    }
    
    sqlite3_finalize(stmt);
    return sqlite3_changes(db);
}

// 获取用户在线状态
int get_online_status(sqlite3 *db, int user_id, int *is_online, time_t *last_active) {
    char *sql = "SELECT is_online, strftime('%s', last_active) "
                "FROM online_status WHERE user_id = ?;";
    
    sqlite3_stmt *stmt;
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
        return -1;
    }
    
    sqlite3_bind_int(stmt, 1, user_id);
    
    rc = sqlite3_step(stmt);
    if (rc == SQLITE_DONE) {
        // 用户不在线状态表中
        sqlite3_finalize(stmt);
        return 0;
    }
    
    if (rc != SQLITE_ROW) {
        fprintf(stderr, "Query failed: %s\n", sqlite3_errmsg(db));
        sqlite3_finalize(stmt);
        return -1;
    }
    
    *is_online = sqlite3_column_int(stmt, 0);
    *last_active = sqlite3_column_int(stmt, 1);
    
    sqlite3_finalize(stmt);
    return 1;
}

// 获取所有在线用户
int get_online_users(sqlite3 *db, int **user_ids, int *count) {
    char *sql = "SELECT user_id FROM online_status WHERE is_online = 1;";
    
    sqlite3_stmt *stmt;
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
        return -1;
    }
    
    // 第一次遍历获取结果数量
    *count = 0;
    while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
        (*count)++;
    }
    
    if (rc != SQLITE_DONE) {
        fprintf(stderr, "Query failed: %s\n", sqlite3_errmsg(db));
        sqlite3_finalize(stmt);
        return -1;
    }
    
    // 重置查询
    sqlite3_reset(stmt);
    
    // 分配内存
    *user_ids = (int *)malloc(*count * sizeof(int));
    if (*user_ids == NULL) {
        fprintf(stderr, "Memory allocation failed\n");
        sqlite3_finalize(stmt);
        return -1;
    }
    
    // 获取结果
    int index = 0;
    while (sqlite3_step(stmt) == SQLITE_ROW) {
        (*user_ids)[index++] = sqlite3_column_int(stmt, 0);
    }
    
    sqlite3_finalize(stmt);
    return 0;
}

// 设置用户离线
int set_user_offline(sqlite3 *db, int user_id) {
    return set_online_status(db, user_id, 0);
}

// 设置用户在线
int set_user_online(sqlite3 *db, int user_id) {
    return set_online_status(db, user_id, 1);
}

// 清理长时间离线的用户
int cleanup_inactive_users(sqlite3 *db, int max_inactive_days) {
    char *sql = "DELETE FROM online_status "
                "WHERE is_online = 0 AND last_active < datetime('now', ?);";
    
    // 构建时间间隔参数
    char interval[50];
    snprintf(interval, sizeof(interval), "-%d days", max_inactive_days);
    
    sqlite3_stmt *stmt;
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
        return -1;
    }
    
    sqlite3_bind_text(stmt, 1, interval, -1, SQLITE_STATIC);
    
    rc = sqlite3_step(stmt);
    if (rc != SQLITE_DONE) {
        fprintf(stderr, "Cleanup failed: %s\n", sqlite3_errmsg(db));
        sqlite3_finalize(stmt);
        return -1;
    }
    
    int rows_affected = sqlite3_changes(db);
    sqlite3_finalize(stmt);
    return rows_affected;
}

// 获取用户最后活动时间
time_t get_last_active_time(sqlite3 *db, int user_id) {
    int is_online;
    time_t last_active;
    int result = get_online_status(db, user_id, &is_online, &last_active);
    
    if (result <= 0) {
        // 用户没有记录，返回0表示未知
        return 0;
    }
    
    return last_active;
}